from django.shortcuts import render, redirect

# Create your views here.
from django.shortcuts import render, HttpResponse
from app03.My_Forms import EmpForm
from app03 import models
from django.core.exceptions import ValidationError
# Create your views here.

#
# def add_emp(request):
#     if request.method == "GET":
#         form = EmpForm()
#         return render(request, "add_emp.html", {"form": form})
#     else:
#         form = EmpForm(request.POST)
#         if form.is_valid():  # 进行数据校验
#             # 校验成功
#             data = form.cleaned_data  # 校验成功的值，会放在cleaned_data里。
#             data.pop('r_salary')
#             print(data)
#
#             models.Emp.objects.create(**data)
#             return HttpResponse(
#                 'ok'
#             )
#             # return render(request, "add_emp.html", {"form": form})
#         else:
#             print(form.errors)    # 打印错误信息
#             clean_errors = form.errors.get("__all__")
#             print(222, clean_errors)
#         return render(request, "add_emp.html", {"form": form, "clean_errors": clean_errors})

def add_emp(request):
    if request.method == "GET":
        form = EmpForm()  # 初始化form对象
        return render(request, "add_emp.html", {"form":form})
    else:
        form = EmpForm(request.POST)  # 将数据传给form对象
        if form.is_valid():  # 进行校验
            data = form.cleaned_data
            data.pop("r_salary")
            models.Emp.objects.create(**data)
            return redirect("/index/")
        else:  # 校验失败
            clear_errors = form.errors.get("__all__")  # 获取全局钩子错误信息
            return render(request, "add_emp.html", {"form": form, "clear_errors": clear_errors})